<template>
  <div class="config-app-page">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :model="searchForm" :inline="true" class="search-form-content">
        <el-form-item label="应用名称">
          <el-input v-model="searchForm.appName" placeholder="请输入应用名称" clearable data-test="search-input" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="searchForm.remark" placeholder="请输入备注" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" data-test="search-button">搜索</el-button>
          <el-button @click="handleReset" data-test="reset-button">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd" data-test="add-button">
        <el-icon><Plus /></el-icon>
        新增应用
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="selectedApps.length === 0" data-test="batch-delete-button">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 应用表格 -->
    <el-card class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="appName" label="应用名称" width="200" />
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="viewApp(scope.row)" data-test="view-button">查看</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)" data-test="edit-button">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)" data-test="delete-button">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="appFormRef"
        :model="appForm"
        :rules="appFormRules"
        label-width="100px"
      >
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="appForm.appName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="appForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { 
  getConfigAppPage, 
  getConfigAppDetail, 
  saveConfigApp, 
  updateConfigApp, 
  deleteConfigApp 
} from '../../../api/configApp.js'

export default {
  name: 'ConfigApplication',
  components: {
    Plus,
    Edit,
    Delete
  },
  setup() {
    const router = useRouter()
    
    // 响应式数据
    const loading = ref(false)
    const searchForm = reactive({
      appName: '',
      remark: ''
    })
    const tableData = ref([])
    const selectedApps = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)
    const appFormRef = ref(null)
    
    const appForm = reactive({
      id: null,
      appName: '',
      remark: ''
    })
    
    const appFormRules = {
      appName: [
        { required: true, message: '请输入应用名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ]
    }
    
    // 加载应用数据
    const loadApps = async () => {
      loading.value = true
      try {
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value,
          param: searchForm.appName || ''
        }
        
        const response = await getConfigAppPage(params)
        
        if (response && response.data) {
          tableData.value = response.data.records || []
          total.value = response.data.total || 0
        } else {
          tableData.value = []
          total.value = 0
        }
        
      } catch (error) {
        ElMessage.error('加载数据失败: ' + (error.message || '网络错误'))
        console.error('加载数据失败:', error)
        tableData.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }
    
    // 生成模拟数据
    const generateMockData = () => {
      const data = []
      const appNames = ['用户管理系统', '订单管理系统', '商品管理系统', '支付系统', '消息推送系统', '数据分析系统', '监控系统', '日志系统']
      const remarks = [
        '负责用户注册、登录、权限管理等功能',
        '处理订单创建、支付、发货等业务流程',
        '管理商品信息、库存、分类等数据',
        '提供支付接口和支付状态管理',
        '负责系统消息和通知推送',
        '数据统计和分析报表生成',
        '系统性能和服务监控',
        '系统日志收集和分析'
      ]
      
      for (let i = 1; i <= pageSize.value; i++) {
        const id = (currentPage.value - 1) * pageSize.value + i
        const appName = appNames[Math.floor(Math.random() * appNames.length)]
        const remark = remarks[Math.floor(Math.random() * remarks.length)]
        
        data.push({
          id,
          appName: `${appName}_${id}`,
          remark,
          createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toLocaleString()
        })
      }
      return data
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      loadApps()
      ElMessage.success('搜索完成')
    }
    
    // 重置搜索
    const handleReset = () => {
      searchForm.appName = ''
      searchForm.remark = ''
      currentPage.value = 1
      loadApps()
    }
    
    // 新增应用
    const handleAdd = () => {
      dialogTitle.value = '新增应用'
      isEdit.value = false
      appForm.id = null
      appForm.appName = ''
      appForm.remark = ''
      dialogVisible.value = true
    }
    
    // 查看应用详情
    const viewApp = async (row) => {
      try {
        const params = { id: row.id }
        const response = await getConfigAppDetail(params)
        
        if (response && response.data) {
          router.push({
            path: '/detail',
            query: {
              type: 'configApp',
              id: row.id,
              action: 'view'
            }
          })
        } else {
          ElMessage.error('获取详情失败')
        }
        
      } catch (error) {
        ElMessage.error('获取详情失败: ' + (error.message || '网络错误'))
        console.error('获取详情失败:', error)
      }
    }
    
    // 编辑应用
    const handleEdit = (row) => {
      dialogTitle.value = '编辑应用'
      isEdit.value = true
      appForm.id = row.id
      appForm.appName = row.appName
      appForm.remark = row.remark
      dialogVisible.value = true
    }
    
    // 删除应用
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个应用吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const params = { ids: [row.id] }
        await deleteConfigApp(params)
        
        ElMessage.success('删除成功')
        loadApps()
        
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败: ' + (error.message || '网络错误'))
          console.error('删除失败:', error)
        }
      }
    }
    
    // 批量删除
    const handleBatchDelete = async () => {
      if (selectedApps.value.length === 0) {
        ElMessage.warning('请选择要删除的应用')
        return
      }
      
      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedApps.value.length} 个应用吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const selectedIds = selectedApps.value.map(app => app.id)
        const params = { ids: selectedIds }
        await deleteConfigApp(params)
        
        ElMessage.success(`成功删除 ${selectedApps.value.length} 个应用`)
        selectedApps.value = []
        loadApps()
        
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败: ' + (error.message || '网络错误'))
          console.error('批量删除失败:', error)
        }
      }
    }
    
    // 保存应用
    const handleSave = async () => {
      try {
        await appFormRef.value.validate()
        
        let response
        if (isEdit.value) {
          // 更新
          response = await updateConfigApp(appForm)
          ElMessage.success('更新成功')
        } else {
          // 新增
          const { id, ...formData } = appForm
          response = await saveConfigApp(formData)
          ElMessage.success('新增成功')
        }
        
        dialogVisible.value = false
        loadApps()
        
      } catch (error) {
        if (error !== false) { // 表单验证失败时error为false
          ElMessage.error('保存失败: ' + (error.message || '网络错误'))
          console.error('保存失败:', error)
        }
      }
    }
    
    // 对话框关闭
    const handleDialogClose = () => {
      appFormRef.value?.resetFields()
    }
    
    // 选择变化
    const handleSelectionChange = (selection) => {
      selectedApps.value = selection
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadApps()
    }
    
    // 当前页变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadApps()
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadApps()
    })
    
    return {
      loading,
      searchForm,
      tableData,
      selectedApps,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      dialogTitle,
      isEdit,
      appForm,
      appFormRules,
      appFormRef,
      handleSearch,
      handleReset,
      handleAdd,
      viewApp,
      handleEdit,
      handleDelete,
      handleBatchDelete,
      handleSave,
      handleDialogClose,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.config-app-page {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.search-form-content {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.operation-buttons {
  margin-bottom: 20px;
}

.operation-buttons .el-button {
  margin-right: 10px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>